package org.example.wikwok.controller;


import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletResponse;
import org.example.wikwok.common.JwtProperties;
import org.example.wikwok.common.JwtUtil;
import org.example.wikwok.common.UtilityClasses;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

//处理视频播放请求，支持自动播放和循环播放。
@RestController
@RequestMapping("/video")
public class VideoPlayerController {
    @RequestMapping(value="/display")
    public void display(String url, String token, HttpServletResponse response) throws IOException {
        if (token == null || token.isEmpty()) {
            return;
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        File file = new File(UtilityClasses.getUploadDir() + url);
        if(!file.exists()){
            response.getOutputStream().close();
            return;
        }
        InputStream inStream=new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int len;
        response.setContentType("video/mp4");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Connection", "Keep-Alive");
        response.setHeader("Accept-Ranges", "bytes");
        while ((len = inStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
        inStream.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
